home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 4579 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.5 KB

  1. Path: mail2news.demon.co.uk!hpl3sn03.cern.ch
  2. From: Dan Pop <danpop@mail.cern.ch>
  3. Newsgroups: comp.lang.c
  4. Subject: Re: variable length string
  5. Date: Tue, 6 Feb 1996 00:14:31 +0100
  6. Organization: CERN European Lab for Particle Physics
  7. Message-ID: <9602052314.AA18664@dxmint.cern.ch>
  8. References: <4f5s97$8sho@tigger.cc.uic.edu>
  9. X-NNTP-Posting-Host: hpl3sn03.cern.ch
  10. X-Newsreader: NN version 6.5.0 #7 (NOV)
  11. X-Mail2News-Path: dxmint.cern.ch!hpl3sn03.cern.ch
  12.  
  13. Qi Zeng <zeng@sunphy1.phy.uic.edu> writes:
  14.  
  15. >Hi, I have a question in reading a variable length string:
  16. >Suppose you want to read from stdin a string, but you do not know how 
  17. >long it will be. You have to assign the string to some char*, to use 
  18. >it say as an element part of node in an linked  list. 
  19. > How can you do that? . 
  20.  
  21. Use fgets with a reasonably sized buffer.  After reading the string,
  22. use strlen to find out its real length, malloc the right amount of memory 
  23. and copy the string there (dropping the terminating '\n').
  24.  
  25. If you want your code to be bullet-proof, check that the last character
  26. of the string is '\n' indeed.  If it isn't, there are more characters to be
  27. read from stdin.  Increase the size of your buffer and repeat the
  28. operation, appending the new characters to the ones already read in the
  29. buffer, until the '\n' shows up.  This can be easily done if the buffer is
  30. allocated with malloc and extended with realloc.
  31.  
  32. Dan
  33. -- 
  34. Dan Pop
  35. CERN, CN Division
  36. Email: danpop@mail.cern.ch 
  37. Mail:  CERN - PPE, Bat. 31 R-004, CH-1211 Geneve 23, Switzerland
  38.